/*
 * action 类型
 */

import ActionTypes from '../config/ActionTypes';
import {
    postFetch
} from '../utils/network/request/HttpExtension.js';
import Session from '../utils/SessionUtils.js';
import {
    Actions
} from 'react-native-router-flux';
import {
    AsyncStorage
} from 'react-native';


import Aes from '../utils/crypto/aes-ctr';
import RSA, {
    RSA_encryptedString
} from '../utils/crypto/RSA';
import {
    setMaxDigits,
    maxDigits
} from '../utils/crypto/BigInt';
setMaxDigits(130);

let encryptedPWD, secretToken, encryptedAesKey = ''
/*
 * 其它的常量
 */

// export const VisibilityFilters = {
//   SHOW_ALL: 'SHOW_ALL',
//   SHOW_COMPLETED: 'SHOW_COMPLETED',
//   SHOW_ACTIVE: 'SHOW_ACTIVE'
// }

/*
 * action 创建函数
 */
// zhaoxing  205
export function LOGIN(username, userpass) {
    return dispatch => {
        generateEncryptPWD(userpass).then(() => {
            dispatch({
                type: (ActionTypes.LOGIN + ActionTypes.FETCH_LOADING_SUFFIX)
            });
            // let params = { LOGON_NAME: username, PASSWORD: userpass };
            var params = {
                LOGON_NAME: username,
                PASSWORD: encryptedPWD,
                CAPTCHA: '',
                DOMAIN_NAME: '',
                CULTURE: 'zh-CN',
                TIMEOFFSET: 0,
                SECRETTOKEN: secretToken,
                ENCRYPTEDKEY: encryptedAesKey,
                LOGON_WAY: 0
            };
            postFetch(ActionCodes.login, params)
                .then(res => {
                    Session.Token = res.TokenGuid;
                    Session.CurrentUser = res;
                  console.log('loginaction', JSON.stringify(res))
                    if(res.TokenGuid != null){
                        AsyncStorage.setItem('userToken', res.TokenGuid)
                    }

                    dispatch({type:(ActionTypes.LOGIN + ActionTypes.FETCH_SUCCESS_SUFFIX)});
                    Actions.replace('tabbar');
                })
                .catch(err => {
                    dispatch({
                        type: (ActionTypes.LOGIN + ActionTypes.FETCH_ERROR_SUFFIX)
                    });
                });
        })

    };
}

const generateEncryptPWD = async pwd => {
    // (async function () {
    let data = await fetch('http://114.255.212.31:8090/Handlers/JSProvider.ashx?encrypt=symmetric', {
        mode: 'no-cors'
    }).then(res => res.text())
    const result = data.split(',');
    var rsaExponent = result[0].split('=')[1].replace(/\'/g, '');
    var rsaModulus = result[1].split('=')[1].replace(/\'/g, '');
    var token = result[2].split('=')[1].replace(/;/g, '').replace(/\'/g, '');

    let aesKey = Math.random()
        .toString(36)
        .slice(0, 20);
    let enPwd = Aes.Ctr.encrypt(pwd, aesKey, 256);
    var rsaKey = new RSA(rsaExponent, '', rsaModulus);
    var enAesKey = RSA_encryptedString(rsaKey, aesKey);
    encryptedPWD = enPwd
    secretToken = token
    encryptedAesKey = enAesKey
    
    // })();
}